export const unflatten = (data) => {
    const map = new Map();
    const tree = [];

    // 创建所有节点的映射
    data.forEach((item) => {
        if (map.has(item.id)) {
            console.warn(
                `Duplicate ID found: ${item.id}. Overwriting previous node.`
            );
        }
        map.set(item.id, {
            ...item,
            children: []
        });
    });

    // 检测循环引用的辅助函数
    const hasCycle = (nodeId, parentId) => {
        const visited = new Set();
        let currentId = parentId;
        visited.add(nodeId); // 防止父链回指当前节点

        while (currentId !== undefined) {
            if (visited.has(currentId)) return true; // 发现循环
            visited.add(currentId);
            const parentNode = map.get(currentId);
            currentId = parentNode?.parentId; // 继续向上追溯
        }
        return false;
    };

    // 构建层级关系
    data.forEach((item) => {
        const node = map.get(item.id);
        const parentId = item.parentId;

        // 处理有父节点的情况
        if (parentId != null) {
            if (map.has(parentId)) {
                // 检测循环引用
                if (hasCycle(item.id, parentId)) {
                    console.error(
                        `Cycle detected! Node ${item.id} cannot be child of ${parentId}. Adding to root.`
                    );
                    tree.push(node);
                } else {
                    map.get(parentId).children.push(node);
                }
            } else {
                // 父节点不存在，提升为根节点
                console.warn(
                    `Parent ID ${parentId} not found for node ${item.id}. Adding to root.`
                );
                tree.push(node);
            }
        } else {
            // 无父节点，直接作为根节点
            tree.push(node);
        }
    });
    console.log(tree, 'treeeeee')
    return tree;
}

/*
* 将树形结构扁平化为数组（支持自定义 children 字段名）
* @param {Array} tree 树形结构数据
* @param {string} [childrenKey='children'] 子节点字段名
* @returns {Array} 扁平化后的数组，包含 id/parentId 关系
*/
export const flatten = (tree, childrenKey = 'children') => {
    const result = [];

    // 递归处理节点
    const traverse = (node, parentId) => {
        if (!node || typeof node !== 'object') return;

        // 提取必要信息并排除 children
        const { [childrenKey]: children, ...rest } = node;
        const flattenedNode = { ...rest, parentId };

        // 加入结果集
        result.push(flattenedNode);

        // 递归处理子节点
        if (Array.isArray(children)) {
            children.forEach(child => traverse(child, node.id));
        }
    };

    // 遍历根节点
    if (Array.isArray(tree)) {
        tree.forEach(root => traverse(root, null)); // 根节点 parentId=null
    }

    return result;
};

export const getNodePath = (tree, targetId) => {
    function traverse (node, path) {
        path.push(node.id) // Add the current node's ID to the path

        if (node.id === targetId) {
            return true // Found the target node
        }

        if (node.children && node.children.length > 0) {
            for (const child of node.children) {
                if (traverse(child, path)) {
                    return true // Target node found in this branch
                }
            }
        }

        path.pop() // Remove the last element as we are backtracking
        return false // Target node not found in this branch
    }

    const path = []
    for (const node of tree) {
        if (traverse(node, path)) {
            return path
        }
    }

    return [] // Target ID not found in the entire tree
}
